/**
 * @description 订单数据操作
 * @author boen
 */

const Order = require('../../models/Order')
const Address = require('../../models/Address')
const Product = require('../../models/Product')

!(async () => {
    // 创建订单
    const requestBody = {
        addressId: '61c194addf063696612554e1',
        shopId: '61c19c7bb131ec1155163374',
        shopName: '沃尔玛',
        isCanceled: false, // 订单是否被取消
        products: [{
                id: '61c1a0f0793482690d9d0870',
                num: 5, // 购买数量
            },
            {
                id: '61c1a0f0793482690d9d0873',
                num: 2
            }
        ]
    }
 
    // 获取address
    const address = await Address.findById(requestBody.addressId)
    // 获取商品列表 ['商品1 id',...]
    const pIds = requestBody.products.map( item => item.id)
    const productList = await Product.find({
        shopId: requestBody.shopId,
        _id: {
            $in: pIds
        }
    })
    console.log("productList：",productList);
    // 整合商品购买数量
    const productListWithSales = productList.map(p => {
        const id = p._id.toString()
        const filterProducts = requestBody.products.filter(item => item.id === id)
        if(filterProducts.length === 0) {
            throw Error('未找到匹配的销量数据')
        }
        return {
            product: p,
            orderSales: filterProducts[0].num
        }
    })
    console.log("productListWithSales",productListWithSales);

    await Order.create({
        username: 'boen',
        shopId: requestBody.shopId,
        shopName: requestBody.shopName,
        isCanceled: requestBody.isCanceled,
        address,
        products: productListWithSales
    })
})()